var http = require('http'),
    fs = require('fs'),
    url = require('url'),
    path = require('path'),
    mime = require('./mime');

http.createServer(
		function(request, response){
			var urlPath = url.parse(request.url).pathname;
			var localPath = __dirname + '/webroot' + urlPath;
			
			path.exists(localPath, function(exists){
				if(exists){
					fs.readFile(localPath, 'binary', function(err, data){
						if(err)
							throw err;
						var ext = path.extname(urlPath);
						ext = ext ? ext.slice(1) : 'unknown';
						console.log(ext);
						
						var contentType = mime.types[ext] || "text/plain";
						console.log(contentType);
						
						response.writeHead(200,{'Content-Type': contentType});
							
						response.write(data, 'binary');
						response.end();
					});
				}
				else{
					response.end('404 File not found.');
				}
			});

		}).listen(8080);

